using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using WP.Commons;
using WP.DB;
using System.Windows.Forms;
using System.IO;
using WP.Controls.OutlookStyleNavigateBar;
namespace WoodproOfficeAddin
{
    public class OfficeAddin
    {

        private bool[] m_bPermit = new bool[13];
      //  private frmOutLookAddinMain frmMDIWindow = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strFormName"></param>
        /// <param name="formStatus">AddNew = 0,Update,Query,Delete,Loading</param>
        /// <param name="lRecId"></param>
        /// <returns></returns>
        /// 
        public void ShowForm(string strMenuID, Form frmMDIForm)
        {
            frmOutLookAddinMain frmMain=  frmMDIForm as  frmOutLookAddinMain ;
            if (frmMain != null)
            {
                 MenuInfo mInfo = DataFunctions.GetMenuInfo(strMenuID);
                 frmMain.ShowForm(mInfo);  
            }
        }
        public bool GetWoodproOutLookMenu(out DataView dvHdr, out DataView dvDtl)
        {
            dvHdr = null;
            dvDtl = null;
            try
            {
                DataTable dtHdr = new DataTable();
                
                //dtHdr.ReadXml(Environment.CurrentDirectory + "\\" + "mOutLookAddinMenuHdr.XML");
                //DataTable dtdtl = new DataTable();
                //dtdtl.ReadXml(Environment.CurrentDirectory + "\\" + "mOutLookAddinMenuDtl.XML");
              //  AppDomain.CurrentDomain.SetDynamicBase(AppDomain.CurrentDomain.BaseDirectory);
                //AppDomain
                //AppDomainSetup app = new AppDomainSetup();
                //app.ApplicationName = "WoodproOutLookAddin";
                //app.DynamicBase = AppDomain.CurrentDomain.BaseDirectory;
                 
                //AppDomain.CurrentDomain.SetDynamicBase(AppDomain.CurrentDomain.BaseDirectory);  
                dtHdr.ReadXml(AppDomain.CurrentDomain.BaseDirectory  +"\\" + "mOutLookAddinMenuHdr.XML");
                DataTable dtdtl = new DataTable();
                dtdtl.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "\\" + "mOutLookAddinMenuDtl.XML");
                dvHdr = dtHdr.DefaultView;
                dvDtl = dtdtl.DefaultView;
                string strUserName = (new LoginUtil()).GetWinUserName();
                dvHdr.RowFilter = "UserName='" + strUserName + "'";
                dvDtl.RowFilter = "UserName='" + strUserName + "'";
                return true;
            }
            catch(Exception ex)
            {
                MsgBoxEx.Show(ex.Message);   
                return false;
            }
        }
        public bool login(string strOutlookMenuName, string strUserName, string strPassword, string strServerName, string strDB, bool blnIsWindowAuthority,out string strCompanyName,out Form frmMDIForm )
        {
            //frmLogin flogin = new frmLogin();
            //string strUserName = "", strPassword = "", strServerName = "", strDB = "";
            //bool blnIsWindowAuthority = false;
            //bool bLogSuccess = flogin.login(out  strUserName, out  strPassword, out strServerName, out strDB, out blnIsWindowAuthority);
            //flogin.Close();
            //return bLogSuccess;
          /// help://MS.VSCC/MS.MSDNVS.2052/cpref/html/frlrfsystemreflectionmethodbaseclassinvoketopic.htm
         //   AppDomain.CreateDomain(@"D:\Woodpro\WoodproInsight\WoodproInsightSetup\Debug");
      //      AppDomain.CreateDomain(@"D:\Woodpro\WoodproInsight\WoodproInsightSetup\Debug");
            frmMDIForm = null;
            bool bLogSuccess = false;
            strCompanyName = "";
            try
            {

                if (strUserName.TrimEnd() == "")
                {
                    strUserName = (new LoginUtil()).GetWinUserName(); 
                }

                Cursor.Current = Cursors.WaitCursor;
                if (strServerName.Trim() == "")
                {
                    MsgBoxEx.Show(Msg.Select("Server name can not be blank.", DataFunctions.GetMsg(this.GetType().FullName, "MSG_ServerNameCanNotBeBlank")), SysVar.WarnTitle);
                    return false;
                }
                if (strDB.Trim() == "")
                {
                    MsgBoxEx.Show(Msg.Select("Database name can not be blank.", DataFunctions.GetMsg(this.GetType().FullName, "MSG_DBNameCanNotBeBlank")), SysVar.WarnTitle);
                    return false;
                }

                string strConnectionPara = "data source=" + strServerName.Replace((char)(29), ' ').TrimEnd() + ";database=" + strDB.Replace((char)(29), ' ').TrimEnd() + ";Connect Timeout=90;";
                if (blnIsWindowAuthority)
                    DBAccess.ConnectionDBString = strConnectionPara + "Trusted_Connection=yes;";
                else
                    DBAccess.ConnectionDBString = strConnectionPara + "uid=" + strUserName + ";pwd=" + strPassword;

                DBAccess dBAccess = new DBAccess(false, false);

                InitSystem(strUserName, strDB, strServerName);
                strCompanyName = SysVar.UserCompany; 
                if (blnIsWindowAuthority && strUserName.Trim() == "")
                {
                    MsgBoxEx.Show(Msg.Select("Login name can not be blank.", DataFunctions.GetMsg(this.GetType().FullName, "MSG_LoginNameCanNotBeBlank")), SysVar.WarnTitle);
                    return false;
                }

                bLogSuccess = true;

                if (bLogSuccess)
                {
                    if (!InitiaUserAuthority())
                    {
                        MsgBoxEx.Show(Msg.Select("You have no permission to access system.", DataFunctions.GetMsg(this.GetType().FullName, "MSG_HaveNoPermissionToAccessSystem")), SysVar.WarnTitle);
                        return false;
                    }
                }

                SysVar.CurrrentColorTable = new ProfessionalColorTable();
                SetColorTheme();
                frmMDIForm = new frmOutLookAddinMain(strOutlookMenuName);
                //SysVar.MDIParentForm = frmMDIWindow; 
                SysVar.IsByOutlookCallBy = true; 
            }
            catch (Exception ex)
            {
                MsgBoxEx.Show(ex.Message, SysVar.WarnTitle);
                return false;
            }


            return true;
        }
        private void InitSystem(string strUserName, string strDB, string strServer)
        {
            DBAccess dbcon = new DBAccess(false, false);

            SysVar.UserName = strUserName;

            SysVar.DatabaseName = strDB;
            SysVar.ServerName = strServer;

            SysVar.UserBrnNo = DataFunctions.GetFieldValue(dbcon, "mUser", "BranchNo", "UserName ='" + SysVar.UserName + "'");
            SysVar.UserLocNo = DataFunctions.GetFieldValue(dbcon, "mUser", "Location", "UserName ='" + SysVar.UserName + "'");
            SysVar.UserCompany = DataFunctions.GetmMiscValue(dbcon, "CompanyName", "m");
            SysVar.CodeSignNo = CvtFunc.ToString(DataFunctions.GetmMiscValue(dbcon, "CodeSignNo", "m"));
            SysVar.CostScale = Convert.ToInt32(DataFunctions.GetmMiscValue(dbcon, "CostScale", "im"));
            SysVar.PriceScale = Convert.ToInt32(DataFunctions.GetmMiscValue(dbcon, "PriceScale", "im"));
            SysVar.QtyScale = Convert.ToInt32(DataFunctions.GetmMiscValue(dbcon, "QuantityScale", "im"));
            SysVar.CustomerName = BaseFunctions.GetCurrentCusomterName();
            SysVar.IsConsolidationGLProject = DataFunctions.GetmSwitchValue(dbcon, "IsConGL", "m");
            int iSecondTimes = CvtFunc.ToInt(DataFunctions.GetmMiscValue(dbcon, "DefaultKeepMessageboxTimes", "m"));
            SysVar.DefKeepMsgTimes = (iSecondTimes <= 0 ? 5 : iSecondTimes);

            SysVar.CostScale = (SysVar.CostScale <= 0 ? 2 : SysVar.CostScale);
            SysVar.PriceScale = (SysVar.PriceScale <= 0 ? 2 : SysVar.PriceScale);
            SysVar.QtyScale = (SysVar.QtyScale <= 0 ? 2 : SysVar.QtyScale);

            SysVar.SalesCostType = (SalesCostType)Convert.ToInt32(DataFunctions.GetmMiscValue(dbcon, "UseCostType", "OE"));
            SysVar.CurrentSalesCostType = SysVar.SalesCostType;
            SysVar.ReportTitle = DataFunctions.GetmMiscValue("CompanyName", "m");

            #region Look up key
            string strKeyChar = DataFunctions.GetmMiscValue(dbcon, "LookUpKeyByCode", "M").Trim().ToUpper();
            switch (strKeyChar)
            {
                case "F6":
                    SysVar.SystemKey.LookUPKey = Keys.F6;
                    break;
                case "F7":
                    SysVar.SystemKey.LookUPKey = Keys.F7;
                    break;
                case "F8":
                    SysVar.SystemKey.LookUPKey = Keys.F8;
                    break;
                default:
                    SysVar.SystemKey.LookUPKey = Keys.F5;
                    break;
            }
            strKeyChar = DataFunctions.GetmMiscValue(dbcon, "LookUpKeyByDescription", "M").Trim().ToUpper();
            switch (strKeyChar)
            {
                case "F5":
                    SysVar.SystemKey.LookUPSecKey = Keys.F5;
                    break;
                case "F7":
                    SysVar.SystemKey.LookUPSecKey = Keys.F7;
                    break;
                case "F8":
                    SysVar.SystemKey.LookUPSecKey = Keys.F8;
                    break;
                default:
                    SysVar.SystemKey.LookUPSecKey = Keys.F6;
                    break;
            }
            #endregion
            #region Search key
            strKeyChar = DataFunctions.GetmMiscValue(dbcon, "SearchKeyByCode", "M").Trim().ToUpper();
            switch (strKeyChar)
            {
                case "F9":
                    SysVar.SystemKey.SearchByCodeKey = Keys.F9;
                    break;
                case "F10":
                    SysVar.SystemKey.SearchByCodeKey = Keys.F10;
                    break;
                case "F11":
                    SysVar.SystemKey.SearchByCodeKey = Keys.F11;
                    break;
                case "F12":
                    SysVar.SystemKey.SearchByCodeKey = Keys.F12;
                    break;
                default:
                    SysVar.SystemKey.SearchByCodeKey = Keys.Down;
                    break;
            }
            strKeyChar = DataFunctions.GetmMiscValue(dbcon, "SearchKeyByDescription", "M").Trim().ToUpper();
            switch (strKeyChar)
            {
                case "F9":
                    SysVar.SystemKey.SearchByNameKey = Keys.F9;
                    break;
                case "F10":
                    SysVar.SystemKey.SearchByNameKey = Keys.F10;
                    break;
                case "F11":
                    SysVar.SystemKey.SearchByNameKey = Keys.F11;
                    break;
                case "F12":
                    SysVar.SystemKey.SearchByNameKey = Keys.F12;
                    break;
                default:
                    SysVar.SystemKey.SearchByNameKey = Keys.Down;
                    SysVar.SystemKey.SearchByNameShiftKey = Keys.Shift;
                    break;
            }
            #endregion

            #region set default language
            int iDftLanguage = CvtFunc.ToInt(DataFunctions.GetmMiscValue(dbcon, "DefaultLanguage", "M"));
            switch (iDftLanguage)
            {
                case 1:
                    SysVar.DftLanguage = "Language1";
                    break;
                case 2:
                    SysVar.DftLanguage = "Language2";
                    break;
                case 3:
                    SysVar.DftLanguage = "Language3";
                    break;
                case 4:
                    SysVar.DftLanguage = "Language4";
                    break;
                case 5:
                    SysVar.DftLanguage = "Language5";
                    break;
                case 6:
                    SysVar.DftLanguage = "Language6";
                    break;
                default:
                    SysVar.DftLanguage = "Language1";
                    break;
            }
            #endregion
            SysVar.ErrTitle = Msg.Select("Error", DataFunctions.GetMsg("ErrTitle"));
            SysVar.SaveChangeTitle = Msg.Select("Save Change", DataFunctions.GetMsg("SaveChange"));
            SysVar.InformationTitle = Msg.Select("Information", DataFunctions.GetMsg("Information"));
            SysVar.ConfirmTitle = Msg.Select("Confirm", DataFunctions.GetMsg("Confirm"));
            SysVar.QueryTitle = Msg.Select("Query", DataFunctions.GetMsg("Query"));

            SysVar.AbleToExcel = DataFunctions.GetFieldValue(dbcon, "mUser", "AbleToExcel", "UserName ='" + SysVar.UserName + "'") == "True";

            SysVar.WarnTitle = Msg.Select("Warning", DataFunctions.GetMsg("WarnTitle"));
            SysVar.TraderPrompt = DataFunctions.GetmMiscValue("TraderPrompt", "m").Trim() == string.Empty ? "Trader" : DataFunctions.GetmMiscValue("TraderPrompt", "m").Trim();
            SysVar.CheckPrompt = DataFunctions.GetmMiscValue("CheckPrompt", "m").Trim() == string.Empty ? "Check" : DataFunctions.GetmMiscValue("CheckPrompt", "m").Trim();
            dbcon.CloseCon();

        }
        private bool InitiaUserAuthority()
        {

            bool bInitiaUserAuthority = false;
            string strSql;
            DataTable dtGroup, dtPermit;
            DataRow drGroup;
            DataView dvPermit;
            DBAccess dBAccess = new DBAccess(false, false);
            int iField;
            int i;

            strSql = "SELECT glSecurGrp,apSecurGrp,arSecurGrp,oeSecurGrp,";
            strSql += "imSecurGrp,poSecurGrp,rmSecurGrp,twSecurGrp,tpSecurGrp,";
            strSql += "smSecurGrp,mfSecurGrp,pdSecurGrp,CRMSecurGrp FROM mUser WHERE UserName='" + SysVar.UserName.Trim() + "'";

            dtGroup = dBAccess.GetDataSet(strSql).Tables[0];

            if (dtGroup.Rows.Count == 0)
            {
                return bInitiaUserAuthority;
            }

            strSql = @"SELECT Permit01, Permit02, Permit03, Permit04, Permit05, Permit06, Permit07,  
                     Permit08, Permit09, Permit10, Permit11, Permit12, Permit13, Permit14, Permit15,
                     Permit16, Permit17, Permit18, Permit19, Permit20, Permit21, Permit22, Permit23,
                     Permit24, Permit25, Permit26, Permit27, Permit28, Permit29, Permit30, MenuId 
                     From mMenu where substring(Menuid,4,9)='000000000' ORDER BY MenuID";

            dtPermit = dBAccess.GetDataSet(strSql).Tables[0];

            for (i = 0; i < dtGroup.Columns.Count; i++)
            {
                drGroup = dtGroup.Rows[0];

                dvPermit = dtPermit.DefaultView;
                dvPermit.RowFilter = "MenuID='" + GetMenuID(i) + "'";

                if (dvPermit.Count == 1)
                {
                    iField = Int32.Parse(drGroup[i].ToString()) - 1;
                    SetButtonEnabled(dvPermit[0][iField].ToString(), i, dvPermit[0]["MenuID"].ToString());
                }
            }

            bInitiaUserAuthority = InitiaMenuPermit();
            dBAccess.CloseCon();

            return bInitiaUserAuthority;
        }
        private void SetButtonEnabled(string p_strPermit, int p_iIndex, string p_strMenuId)
        {
            if (p_strPermit.Trim().ToUpper() != "N" && p_strMenuId == GetMenuID(p_iIndex))
                m_bPermit.SetValue(true, p_iIndex);
        }
        private string GetMenuID(int p_iIndex)
        {
            string strMenuID = "";

            switch (p_iIndex)
            {
                case (int)SystemModules.GL:
                    strMenuID = "010000000000";
                    break;
                case (int)SystemModules.AP:
                    strMenuID = "020000000000";
                    break;
                case (int)SystemModules.AR:
                    strMenuID = "030000000000";
                    break;
                case (int)SystemModules.CR:
                    strMenuID = "036000000000";
                    break;
                case (int)SystemModules.OE:
                    strMenuID = "040000000000";
                    break;
                case (int)SystemModules.IM:
                    strMenuID = "050000000000";
                    break;
                case (int)SystemModules.PO:
                    strMenuID = "060000000000";
                    break;
                case (int)SystemModules.RM:
                    strMenuID = "090000000000";
                    break;
                case (int)SystemModules.TW:
                    strMenuID = "100000000000";
                    break;
                case (int)SystemModules.TP:
                    strMenuID = "200000000000";
                    break;
                case (int)SystemModules.ES:
                    strMenuID = "600000000000";
                    break;
                case (int)SystemModules.MF:
                    strMenuID = "900000000000";
                    break;

                case (int)SystemModules.PD:
                    strMenuID = "120000000000";
                    break;

            }
            return strMenuID;

        }
        private bool InitiaMenuPermit()
        {
            bool bInitiaMenuPermit;
            SysVar.MenuGLPermit = false;
            SysVar.MenuAPPermit = false;
            SysVar.MenuARPermit = false;
            SysVar.MenuOEPermit = false;
            SysVar.MenuIMPermit = false;
            SysVar.MenuPOPermit = false;
            SysVar.MenuRMPermit = false;
            SysVar.MenuTWPermit = false;
            SysVar.MenuTPPermit = false;
            SysVar.MenuESPermit = false;
            SysVar.MenuMFPermit = false;
            SysVar.MenuPDPermit = false;

            if (m_bPermit[(int)SystemModules.GL]) SysVar.MenuGLPermit = true;
            if (m_bPermit[(int)SystemModules.AP]) SysVar.MenuAPPermit = true;
            if (m_bPermit[(int)SystemModules.AR]) SysVar.MenuARPermit = true;
            if (m_bPermit[(int)SystemModules.OE]) SysVar.MenuOEPermit = true;
            if (m_bPermit[(int)SystemModules.IM]) SysVar.MenuIMPermit = true;
            if (m_bPermit[(int)SystemModules.PO]) SysVar.MenuPOPermit = true;
            if (m_bPermit[(int)SystemModules.RM]) SysVar.MenuRMPermit = true;
            if (m_bPermit[(int)SystemModules.TW]) SysVar.MenuTWPermit = true;
            if (m_bPermit[(int)SystemModules.TP]) SysVar.MenuTPPermit = true;
            if (m_bPermit[(int)SystemModules.ES]) SysVar.MenuESPermit = true;
            if (m_bPermit[(int)SystemModules.MF]) SysVar.MenuMFPermit = true;
            if (m_bPermit[(int)SystemModules.PD]) SysVar.MenuPDPermit = true;


            bInitiaMenuPermit = SysVar.MenuGLPermit || SysVar.MenuAPPermit || SysVar.MenuARPermit ||
            SysVar.MenuOEPermit || SysVar.MenuIMPermit || SysVar.MenuPOPermit || SysVar.MenuRMPermit ||
            SysVar.MenuTWPermit || SysVar.MenuTPPermit || SysVar.MenuESPermit || SysVar.MenuMFPermit ||
            SysVar.MenuPDPermit ;

            return bInitiaMenuPermit;
        }


        private void SetColorTheme()
        {
            ProfessionalColorTable cTable = null;
            string strColorTheme = GetColorTheme();
            switch (strColorTheme)
            {
                case "ColorTable.SystemColor":
                    cTable = new ProfessionalColorTable();
                    break;
                case "ColorTable.Office2003Blue":
                    cTable = new Office2003BlueColorTable();
                    break;
                case "ColorTable.Office2003Silver":
                    cTable = new Office2003SilverColorTable();
                    break;
                case "ColorTable.Office2003Olive":
                    cTable = new Office2003OliveColorTable();
                    break;
                case "ColorTable.Office2007Blue":
                    cTable = new Office2007BlueColorTable();
                    break;
                case "ColorTable.Office2007Black":
                    cTable = new Office2007BlackColorTable();
                    break;
                case "ColorTable.Office2007Silver":
                    cTable = new Office2007SilverColorTable();
                    break;
                default:
                    break;
            }


            if (cTable != null)
            {
                ToolStripManager.Renderer = new OfficeRenderer(cTable);
                SysVar.CurrrentColorTable = cTable;
            }


        }


        private string GetColorTheme()
        {
            try
            {
                using (StreamReader sr = new StreamReader(Environment.CurrentDirectory + @"\ColorThemeSettings.dat"))
                {
                    while (true)
                    {
                        string s = sr.ReadLine();
                        if (s != null && s.IndexOf("ColorTable=") >= 0)
                        {
                            return s.Trim().Substring("ColorTable=".Length);
                        }
                        else if (s == null)
                        {
                            return "";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return "";
            }
        }



    }
}
